﻿using System.Windows ;
using System.Windows.Controls ;
using System.Windows.Interactivity ;
using System.Windows.Media ;
using System ;

namespace OpenLightGroup.Common.Interactivity
{
    public class ScalingFontBehavior : Behavior<TextBlock>
    {
        // Using a DependencyProperty as the backing store for MinFontSize.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MinFontSizeProperty =
        DependencyProperty.Register ( "MinFontSize", typeof(double), typeof(ScalingFontBehavior), new PropertyMetadata ( null ) ) ;

        private bool _textHintingModeSet = false ;

        public ScalingFontBehavior ( )
        {
        }

        public double MinFontSize
        {
            get
            {
                return (double)this.GetValue ( MinFontSizeProperty ) ;
            }
            set
            {
                this.SetValue ( MinFontSizeProperty, value ) ;
            }
        }

        protected override void OnAttached ( )
        {
            base.OnAttached ( ) ;
            this.AssociatedObject.LayoutUpdated += new EventHandler ( AssociatedObject_LayoutUpdated ) ;

        }

        protected override void OnDetaching ( )
        {
            base.OnDetaching ( ) ;

            this.AssociatedObject.LayoutUpdated -= AssociatedObject_LayoutUpdated ;
        }

        private bool GetIsTextClippingHorizontally ( )
        {
            return this.AssociatedObject.ActualWidth > this.AssociatedObject.Width ;
        }

       private void AssociatedObject_LayoutUpdated ( object sender, EventArgs e )
        { 
            if ( this.AssociatedObject.FontSize > this.MinFontSize && ( this.GetIsTextClippingHorizontally ( ) || this.GetIsTextClippingVertically ( ) ) )
            {
                if ( !this._textHintingModeSet )
                {
                    TextOptions.SetTextHintingMode ( this.AssociatedObject, TextHintingMode.Animated ) ;
                    this._textHintingModeSet = true ;
                }

                this.AssociatedObject.FontSize -= 1 ;
            }
        }

        private bool GetIsTextClippingVertically ( )
        {
            bool wrapping = ( this.AssociatedObject.TextWrapping == TextWrapping.Wrap ) ;

            return wrapping && this.AssociatedObject.ActualHeight > this.AssociatedObject.Height ;
        }
    }
}